# -*- coding: utf-8 -*-
'''
Created on 25-10-2012

@author: LONG HOANG GIANG
'''
from CrawlerLib import commonlib, AESCipher
from CrawlerLib.sqlitehelper import SQLiteHelper
from Model.storymodelv2 import StoryModel
import re
import os

def convert(src, dest='', encrypt=False):
    cipher = AESCipher.AESCipher("longhoanggiang")
    if dest.strip() == '':
        dest = "/longhoanggiang/database/_{0}".format(os.path.basename(src))
    dbSrc = SQLiteHelper(src)
    dbDest = StoryModel(dest)
    dbDest.open(True)
    dbSrc.execute("select tblChapters.title, tblDetail.detail from tblChapters, tblDetail where tblChapters.id=tblDetail.chapterId")
    rows = dbSrc.fetchall()
    for row in rows:
        title = row[0]
        detail = row[1]
        title = title.replace("CHƯƠNG", "CHAP").strip()
        title = title.replace('  ', ' ')
        title = commonlib.toUpper(title)
        print title
        if encrypt:
            title = cipher.encrypt(title)
            detail = cipher.encrypt(detail)
        detail = re.sub(ur"^(<br[^>]*>\s*)*", "", detail)
        detail = re.sub(ur"(\s*<br[^>]*>\s*){3,}", "<br /><br />", detail)
        detail = re.sub(ur"<b>(Chương \d+)</b> *<br /> *<br />", "<b>\\1</b><br /><hr /><br />", detail)
        detail = detail.strip()
        if appendTitle:
            detail = '''<b>{0}</b><br /><br />{1}'''.format(title, detail)
        print detail[:150]    
        dbDest.add_story(title, detail, 0)
    dbSrc.close()
    dbDest.close()
    


if __name__ == '__main__':
    
    src = '/longhoanggiang/moapsoft/{0}'.format('bday')
    appendTitle = False
    convert(src)
    
    print '> Finished'